package cn.topevery.garden.dal.util;

import cn.hutool.core.lang.TypeReference;
import cn.hutool.core.util.BooleanUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import cn.topevery.garden.entity.po.basic.RedisData;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import java.time.LocalDateTime;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import java.util.function.Function;
import java.util.stream.Collectors;

@Slf4j
@Component
public class CacheClient {
  /*  private final StringRedisTemplate stringRedisTemplate;
    private static final ExecutorService CACHE_REBUILD_EXECUTOR = Executors.newFixedThreadPool(10);

    public CacheClient(StringRedisTemplate stringRedisTemplate) {
        this.stringRedisTemplate = stringRedisTemplate;
    }

    //将空值存入redis，并设置过期时间，解决缓存穿透问题
    public <R, ID> R queryWithPassThrough(String keyPrefix, ID id, Class<R> type, Function<ID, R> dbFallback, Long normalTime, Long nullTime, TimeUnit unit) {
        String key = keyPrefix + id;
        //1.从redis中查询缓存
        String json = stringRedisTemplate.opsForValue().get(key);
        //2.判断是否存在
        if (StrUtil.isNotBlank(json)) {
            //3.存在，直接返回
            return JSONUtil.toBean(json, type);
        }
        // 判断命中的是否是空串
        if (json != null) {
            // 返回一个错误信息
            return null;
        }
        // 4.不存在，根据id查询数据库
        R r = dbFallback.apply(id);
        if (r == null) {
            // 将空值写入redis
            stringRedisTemplate.opsForValue().set(key, "", nullTime, unit);
            //返回错误信息
            return null;
        }
        // 6.存在，写入redis
        stringRedisTemplate.opsForValue().set(key, JSONUtil.toJsonStr(r), normalTime, unit);
        return r;
    }

    //利用互斥锁解决缓存击穿问题
    public <R, ID> R queryWithMutex(String keyPrefix, ID id, Class<R> type, Function<ID, R> dbFallback,
                                    String lockKeyPrefix, Long lockTime, Long normalTime, Long nullTime, TimeUnit unit) {
        String key = keyPrefix + id;
        //1.从redis中查询缓存
        String json = stringRedisTemplate.opsForValue().get(key);
        //2.判断是否存在
        if (StrUtil.isNotBlank(json)) {
            //3.存在，直接返回
            return JSONUtil.toBean(json, type);
        }
        //4.不存在，且为空串返回错误
        if (json != null) {//为空串“”
            //返回一个错误信息
            return null;
        }
        //4. 不存在,实现缓存重构
        //4.1 获取互斥锁
        String lockKey = lockKeyPrefix + id;
        R r = null;
        try {
            boolean isLock = tryLock(lockKey, lockTime);
            // 4.2 判断否获取成功
            if (!isLock) {
                //4.3 失败，则休眠重试
                TimeUnit.MILLISECONDS.sleep(50);
                return queryWithMutex(keyPrefix, id, type, dbFallback, lockKeyPrefix, lockTime, normalTime, nullTime, unit);//重新尝试
            }
            //4.4 成功，根据id查询数据库
            r = dbFallback.apply(id);
            // 5.不存在，返回错误
            if (r == null) {
                //将空值写入redis，防止缓存穿透
                stringRedisTemplate.opsForValue().set(key, "", nullTime, unit);
                //返回错误信息
                return null;
            }
            //6.存在，写入redis
            stringRedisTemplate.opsForValue().set(key, JSONUtil.toJsonStr(r), normalTime, unit);
        } catch (Exception e) {
            throw new RuntimeException(e);
        } finally {
            //释放锁
            stringRedisTemplate.delete(lockKey);
        }
        //7.返回
        return r;
    }

    public <R, ID> R queryWithLogicalExpire(String keyPrefix, ID id, Class<R> type, Function<ID, R> dbFallback,
                                            String lockKeyPrefix, Long lockTime, Long normalTime, Long nullTime, TimeUnit unit) {
        String key = keyPrefix + id;
        //1.从redis中查询缓存
        String json = stringRedisTemplate.opsForValue().get(key);
        //2.判断是否存在
        if (StrUtil.isBlank(json)) {//缓存未命中
            //3.查询并重建缓存 返回
            return queryAndSetToRedis(key, id, dbFallback, normalTime, nullTime, unit);
        }
        // 4.命中，需要先把json反序列化为对象
        RedisData<R> redisData = JSONUtil.toBean(json, new TypeReference<RedisData<R>>() {
        }, false);
        R r = JSONUtil.toBean((JSONObject) redisData.getData(), type);
        LocalDateTime expireTime = redisData.getExpireTime();
        // 5.判断是否过期
        if (expireTime.isAfter(LocalDateTime.now())) {
            // 5.1.未过期，直接返回店铺信息
            return r;
        }
        // 5.2.已过期，需要缓存重建
        // 6.缓存重建
        // 6.1.获取互斥锁
        String lockKey = lockKeyPrefix + id;
        boolean isLock = tryLock(lockKey, lockTime);
        // 6.2.判断是否获取锁成功
        if (isLock) {
            // 6.3.成功，开启独立线程，实现缓存重建
            CACHE_REBUILD_EXECUTOR.submit(() -> {
                try {
                    //查询数据库和重建缓存
                    queryAndSetToRedis(key, id, dbFallback, normalTime, nullTime, unit);
                } catch (Exception e) {
                    throw new RuntimeException(e);
                } finally {
                    //释放锁
                    stringRedisTemplate.delete(lockKey);
                }
            });
        }
        //7.返回
        return r;
    }

    private <ID, R> R queryAndSetToRedis(String key, ID id, Function<ID, R> dbFallback, Long normalTime, Long nullTime, TimeUnit unit) {
        //查询数据库
        R r = dbFallback.apply(id);
        Long newExpireTime = normalTime;
        if (r == null) {
            newExpireTime = nullTime;
        }
        //重建缓存
        this.setWithLogicalExpire(key, r, newExpireTime, unit);
        return r;
    }

    private <T> void setWithLogicalExpire(String key, T t, Long time, TimeUnit unit) {
        // 设置逻辑过期
        RedisData<T> shopRedisData = new RedisData<>(LocalDateTime.now().plusSeconds(unit.toSeconds(time)), t);
        //写入redis,强制给一个较长的过期时间
        stringRedisTemplate.opsForValue().set(key, JSONUtil.toJsonStr(shopRedisData), 1L, TimeUnit.DAYS);
    }

    private boolean tryLock(String lockKey, Long lockTime) {
        Boolean flag = stringRedisTemplate.opsForValue().setIfAbsent(lockKey, "1", lockTime, TimeUnit.SECONDS);
        return BooleanUtil.isTrue(flag);
    }

    public <R extends List<E>, E, ID> R queryListWithMutex(String keyPrefix, ID id, Class<E> entityType, Function<ID, R> dbFallback,
                                                           String lockKeyPrefix, Long lockTime, Long normalTime, Long nullTime, TimeUnit unit) {
        String key = keyPrefix + id;
        List<E> eList1 = queryListFromRedis(key, entityType);
        if (!CollectionUtils.isEmpty(eList1)) {
            return (R) eList1;
        }
        //4. 不存在,实现缓存重构
        //4.1 获取互斥锁
        String lockKey = lockKeyPrefix + id;
        R r = null;
        try {
            boolean isLock = tryLock(lockKey, lockTime);
            // 4.2 判断否获取成功
            if (!isLock) {
                //4.3 失败，则休眠重试
                TimeUnit.MILLISECONDS.sleep(50);
                return queryListWithMutex(keyPrefix, id, entityType, dbFallback, lockKeyPrefix, lockTime, normalTime, nullTime, unit);//重新尝试
            }
            //获取锁成功应该再次检查Redis缓存是否存在，做DoubleCheck,有缓存无需重建缓存,防止重复更新缓存
            List<E> eList2 = queryListFromRedis(key, entityType);
            if (!CollectionUtils.isEmpty(eList2)) {
                return (R) eList2;
            }
            //4.4 成功，根据id查询数据库
            r = dbFallback.apply(id);
            // 5.不存在，返回错误
            if (r == null) {
                //将空值写入redis，防止缓存穿透
                stringRedisTemplate.opsForList().rightPush(key, "");
                stringRedisTemplate.expire(key, nullTime, unit);
                //返回错误信息
                return null;
            }
            //6.存在，写入redis
            JSONArray jsonArray = JSONUtil.parseArray(r);
            List<String> newList = JSONUtil.toList(jsonArray, String.class);
            stringRedisTemplate.opsForList().rightPushAll(key, newList);
            stringRedisTemplate.expire(key, normalTime, unit);
        } catch (Exception e) {
            throw new RuntimeException(e);
        } finally {
            //释放锁
            stringRedisTemplate.delete(lockKey);
        }
        //7.返回
        return r;
    }

    public <E> List<E> queryListFromRedis(String key, Class<E> entityType) {
        //1.从redis中查询缓存
        List<String> list = stringRedisTemplate.opsForList().range(key, 0, -1);
        //判断是否存在
        if (!CollectionUtils.isEmpty(list)) {
            List<E> resultList = list.stream().map(s -> JSONUtil.toBean(s, entityType)).collect(Collectors.toList());
//            List<E> eList = JSONUtil.toList(JSONUtil.toJsonStr(list), entityType);//转成指定泛型的集合，需要每个元素单独转换，此方法会报错
            //3.存在，直接返回
            return resultList;
        }
        return null;
    }*/
}